<script setup lang="ts">
const showPrivacy = ref<any>(null)
const privacyContractName = ref<string>('《用户隐私保护指引》')

async function init() {
  await nextTick()
  await sleep(300)
  const path = '/pages/home/index'
  uni.reLaunch({
    url: path,
  })
}

function close() {
  // #ifdef MP-WEIXIN
  uni.exitMiniProgram({
    complete: complete => console.log('exitMiniProgram complete', complete),
  })
  // #endif
}

function openPrivacyContract() {
  // #ifdef MP-WEIXIN
  wx.openPrivacyContract({
    complete: complete => console.log('openPrivacyContract complete', complete),
  })
  // #endif
}

function handleAgreePrivacyAuthorization(event) {
  // #ifdef MP-WEIXIN
  console.log('agreePrivacyAuthorization', event)
  showPrivacy.value.close()
  init()
  // #endif
}

async function getPrivacySetting() {
  await nextTick()
  // #ifdef MP-WEIXIN
  wx.getPrivacySetting({
    success: (res) => {
      privacyContractName.value = res.privacyContractName
      if (res.needAuthorization) {
        return showPrivacy.value.open()
      }
      // 未配置或者已同意
      init()
    },
    complete: complete => console.log('getPrivacySetting complete', complete),
  })
  // #endif

  // #ifndef MP-WEIXIN
  init()
  // #endif
}

onLoad(() => {
  getPrivacySetting()
})
</script>

<template>
  <view>
    <!-- #ifndef MP-WEIXIN -->
    <uv-loading-page :loading="true" loading-text="加载中..." font-size="24rpx" />
    <!-- #endif -->

    <!-- #ifdef MP-WEIXIN -->
    <uni-popup ref="showPrivacy" type="bottom" :is-mask-click="false">
      <view class="rounded-t-20rpx bg-[#FFFFFF] px-44rpx pt-32rpx">
        <view class="space-y-24rpx">
          <view>
            <text class="text-32rpx text-[#000000]">
              用户隐私保护提示
            </text>
          </view>
          <view>
            <text class="text-24rpx text-[#000000]">
              感谢您使用本程序，在使用前请您仔细阅读、充分理解并同意
            </text>
            <text class="text-24rpx text-[#165DFF]" @click="openPrivacyContract">
              {{ privacyContractName }}，
            </text>
            <text class="text-24rpx text-[#000000]">
              如您同意该指引，请点击“同意”开始使用本小程序，如您不同意，将无法使用小程序相关功能。
            </text>
          </view>
        </view>
        <view us-flex us-items-center us-justify-between class="gap-x-20rpx py-24rpx">
          <view class="w-214rpx">
            <uv-button text="不同意" type="info" @click="close()" />
          </view>
          <view us-flex-1>
            <uv-button
              text="同意" type="primary" open-type="agreePrivacyAuthorization"
              @agreeprivacyauthorization="handleAgreePrivacyAuthorization"
            />
          </view>
        </view>
      </view>
    </uni-popup>
    <!-- #endif -->
  </view>
</template>

<style lang="scss" scoped></style>

<route name="home" lang="yaml">
layout: 'default'
needLoging: false
style:
  navigationBarTitleText: '加载中'
</route>
